define(function(require) {
	
	var $ = require("jquery1.7");
	var Confirmbox = require("confirmbox");
	var Validator = require("validator");
	var utils = require("utils");
	var ui = require("ui");
	require("zTree");
	require("ztree-exedit");
	require("ztree-excheck");
	
	var ctx = utils.constants.ctx;
	
	var backManagerService = require("bean/backManagerService");
	
	var BlackBox = require("blackbox");
	var blackBox = new BlackBox();
	//添加
	$.post(ctx + '/back/base/roleEditUI',function(data){
		var confirmBox = new Confirmbox({
	        trigger: '#addRole',
	        title: '角色添加',
	        message: data,
	        onConfirm: function() {
	        	role_submit("add");
	        }
	    });
		confirmBox.after("show",function(){
			var validator = new Validator({
	            element: $("#role_form")
	        }).addItem({
	            element: '[name=roleName]',
	            required: true
	        });
		});
		confirmBox.after("hide",function(){
			$("#roleName").val("");
			$("#roleDescn").val("");
		});
	});
	
	//修改
	var updateCb ;
	$(".btn_Modify").bind("click",function(){
		
		var id = $(this).attr("data").replace("role_", "");
		
		$.post(ctx + '/back/base/roleEditUI', {"roleId":id},function(data){
			if(updateCb == null) {
				updateCb = new Confirmbox({
			        title: '用户身份修改',
			        effect: "fade",
			        message: data,
			        onConfirm: function() {
			        	role_submit("update");
			        }
			    });
			} else {
				updateCb.before("show",function(){
					this.set("message",data);
				});
			}
			updateCb.after("show",function(){
				var validator = new Validator({
		            element: $("#role_form")
		        }).addItem({
		            element: '[name=roleName]',
		            required: true
		        });
			});
			updateCb.show();
		});
	});
	
	var role_submit = function (type){
		var name = $("#roleName").val();
		var descn = $("#roleDescn").val();
		var id  = $("#roleId").val();
		if(name == ""){
			$("#roleName").trigger("focus");
			$("#roleName").trigger("blur");
			return false;
		}
		
		var role = {
	 			id : id,
    			name : name,
    			descn : descn
    		};
	 	
	 	try {
	 		ui.mask("#addRole").show("请稍候...");
	 		if (type == "add"){
	 			backManagerService.roleAdd(role)
	 			ui.mask("#addRole").hide();
    	 		alert('添加成功');
	 		} else {
    	 		backManagerService.roleUpdate(role);
		 		alert('修改成功');
	 		}
	 		window.location.reload();
	 	} catch (e){
	 		ui.mask().hide();
			alert(e.message);
	 	}
	}
	
	
	//删除
	$("#deleteRoleList").bind("click",function(){
		if ($('input[name=items]:checkbox:checked').length <= 0) {
			blackBox.alert("请选择用户身份");
			return;
		}
		blackBox.confirm("确定要删除角色信息？",function(isOk){
			if(isOk){
				var array = [];
				$('input[name=items]:checkbox:checked').each(function() {
					
					var id = $(this).attr("id").replace("role_", "");
					array.push(id);   
				});
				
				if (array.length != 0) {
					try{
						ui.mask().show("请稍候...");
						backManagerService.roleDelete(array);
						ui.mask().hide();
						blackBox.alert("删除成功");
						window.location.reload();
					} catch (e) {
						ui.mask().hide();
						blackBox.alert("删除失败:"+e.message);
					}
				} 
			}
		},{
			title:'提示',
			value:'确认'
		});
	});
	
	//角色的分配权限
	var updateRescourceCb;
	$(".btn_resource").bind("click",function(){
		
		var roleId = $(this).attr("role_id").replace("role_", "");
		updateRoleId = parseInt(roleId);
		var role = backManagerService.getRole(updateRoleId);
		if(!role) {
			blackBox.alert("角色不存在！");
			return;
		}
		var resourseIds = role.resourcesId;

		var data = '<div id="role_resource_tree" class="ztree" style="min-height:160px;"></div>';
		
		if(updateRescourceCb == null) {
			updateRescourceCb = new Confirmbox({
				
				trigger: '#role_resource_tree',
				title: "分配权限",
				message: data,
				width : 450,
				onConfirm: function() {
					
					var zTree = $.fn.zTree.getZTreeObj("role_resource_tree");
					var nodes = zTree.getCheckedNodes(true);
					var nodeIds = [];
					for(var i=0; i<nodes.length; i++) {
						nodeIds.push(nodes[i].id);
					}	
					try {

						backManagerService.roleAllotResource(updateRoleId, nodeIds);
				 		alert('分配成功');
				 		window.location.reload();
				 	} catch (e){
						alert('分配失败！<br/>' + e.message);
				 	}
				}
			});
		} else {					
			updateRescourceCb.before('show',function() {

		       this.set('message', data);
		   });
		}
		updateRescourceCb.show();

		//zTree基本设置
		var role_resource_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				check: {
					enable: true,
					chkStyle: "checkbox",
					chkDisabled : false
				},
				async : {
					enable : true,
					url : ctx + "/back/base/resource-json", 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  
					onAsyncSuccess: function() {
						ui.mask().hide();
						var zTree = $.fn.zTree.getZTreeObj("role_resource_tree");
						for(var i=0; i < resourseIds.length; i++) {							
							zTree.checkNode(zTree.getNodeByParam("id", resourseIds[i]), true, false);
						}
					}
		        } 
		};
		$.fn.zTree.init($("#role_resource_tree"), role_resource_setting, []);
		ui.mask().show("请稍候...");
	});
	
	
	$("#searchBtn").bind("click",function(){
		var searchContent = $("#searchInfo").val();
		if(searchContent == null){
			blackBox.alert("请输入搜索内容")
			return false ;
		}
		location.href = ctx+"/back/base/roleList?name="+searchContent;
		
	});
	
})